<?php defined('SYSPATH') or die('No direct script access.');

// Контроллер для работы с аяксом


class Controller_Ajax extends Controller {

	
	public function action_index()
	{
		die();
	}
	public function action_enter()
	{
		if (isset($_POST['login']) && isset($_POST['pass']))
		{
			if (trim($_POST['login'])=='')	$this->outJSON(1,'Введите логин');
			if (trim($_POST['pass'])=='')	$this->outJSON(1,'Введите пароль');
			
			$calc = Model::factory('calc');
			$res = $calc->login($_POST['login'],$_POST['pass']);
			
			if ($res === true) $this->outJSON(0,'');
			else $this->outJSON(1,$res);		
		}	
		die();
	}
	
	public function action_exit()
	{
		$calc = Model::factory('calc')->logout();		
		$this->outJSON(0,'');		
		die();
	}
	public function action_calculate()
	{
		
		if (isset($_POST['oper']) && isset($_POST['num1']) && isset($_POST['num2']))
		{
			if (!is_numeric($_POST['num1']) || !is_numeric($_POST['num2']))  $this->outJSON(1,'Wrong numbers');
			$calc = Model::factory('calc');
			switch ($_POST['oper'])
			{
				case 'divide':case 'multiply':case 'plus':case 'minus':
					
					//$calc->login('admin','123');
					$res = $calc->calculate($_POST['oper'],$_POST['num1'],$_POST['num2']);
					
					$this->outJSON($res['code'],$res['mess']);
					
					break;
				default: $this->outJSON(1,'Wrong operation');
			}			
			
		}
		die();
	}	
	
	
	public function action_calc()
	{
		
		$view = View::factory('calc')->render();
		$this->response->body($view);
		
	}
	
	public function action_form()
	{
		
		$view = View::factory('form')->render();
		$this->response->body($view);
		
	}
	protected function outJSON($code,$mess)
	{
		echo json_encode(array( 'code' => $code, 'mess' => $mess ));
		die();
	}

}
